package com.qt.myboot.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

public class RememberMeConfig {

        @Value("${shiro.cookie-name}")
        private String COOKIE_NAME;
        @Value("${shiro.cipher-key}")
        private String Base64CipherKey;

        /**
         *  可选 
         *  不配置会使用默认的cookie名称
         * @return
         */
        @Bean
        public SimpleCookie simpleCookie() {

            COOKIE_NAME = StringUtils.isEmpty(COOKIE_NAME) ? "shiro-cookie" : COOKIE_NAME;
            SimpleCookie cookie = new SimpleCookie(COOKIE_NAME);
            return cookie;
        }

        /**
         *  配置cookie管理器
         * @param cookie
         * @param securityManager
         * @return
         */
        @Bean
        public CookieRememberMeManager cookieRememberMeManager(Cookie cookie, DefaultWebSecurityManager securityManager) {

            CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
            cookieRememberMeManager.setCookie(cookie);

            /**
             * 不指定固定值，则会在每次系统启动时自动生成新的秘钥
             *  新的秘钥解密不要旧秘钥的Cookie，导致校验失败
             */
            Base64CipherKey = StringUtils.isEmpty(Base64CipherKey) ? "f/SY5TIve5WWzT4aQlABJA==" : Base64CipherKey;
            byte[] cipherKey = Base64.decode(Base64CipherKey);

            /**
             *  配置密码编译器
             */
            cookieRememberMeManager.setCipherService(new AesCipherService());
            cookieRememberMeManager.setCipherKey(cipherKey);

            // 注入到 securityManager
            securityManager.setRememberMeManager(cookieRememberMeManager);

            // 配置cookie失效时间 （-1 为关闭浏览器则关闭）
//            cookie.setMaxAge(-1);

            return cookieRememberMeManager;
        }
    }